package jwanalytics.dbloader;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.log4j.Logger;



import junit.framework.TestCase;
import jwanalytics.utils.date.BaseCalendar;

public class PopulateDateDimensionTest extends TestCase {

	/** Logger for all pages. */
	public static Logger logger = Logger.getLogger("jwanalytics");
	
	public void testIds() throws Exception {
		int counter = 1;
		Props.init(Props.PROPS_FILE, false);
		String startAnalyticsStr = Props.get(Props.PROPS_FILE, "start_analytics_date");
		SimpleDateFormat sdf = new java.text.SimpleDateFormat("yy-mm-dd");
		Date startAnalyticsDate = sdf.parse(startAnalyticsStr);
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime((Date)startAnalyticsDate.clone());		
		
		int maxYear = Integer.parseInt(Props.get(Props.PROPS_FILE, "end_analytics_year"));
		
		Date fetchedDt = null;
		GregorianCalendar fetchedCal = null;

		Connection con = DB.getConnection();		
		while (cal.get(Calendar.YEAR) != maxYear) {
			//check counter on date_dimension table refers to row on this date.
			logger.debug("Cal:"+cal.getTime());
			
			if (Math.random() < 0.05) { //10% of the times test date. Sample test.
				try {
					Integer dateKey= new Integer(counter);
					PreparedStatement prepSt = con.prepareStatement("SELECT * FROM date_dimension WHERE date_key = ?");	
					prepSt.setInt(1, dateKey);
					ResultSet rs = prepSt.executeQuery();
					rs.next();
					//
					fetchedDt = rs.getDate("date");
					fetchedCal = new GregorianCalendar();
					fetchedCal.setTime(fetchedDt);
					assertTrue(fetchedCal.get(Calendar.YEAR) == cal.get(Calendar.YEAR));
					assertTrue(fetchedCal.get(Calendar.MONTH) == cal.get(Calendar.MONTH));
					assertTrue(fetchedCal.get(Calendar.DAY_OF_MONTH) == cal.get(Calendar.DAY_OF_MONTH));
					assertTrue(counter == BaseCalendar.daysSpan(fetchedDt, startAnalyticsDate));
					assertTrue(counter == BaseCalendar.dayIndex(fetchedDt, startAnalyticsDate));						
				} catch(Exception e) {
					logger.error("WAERROR0011:"+e);
					logger.error("WAERROR0011cont:Date not found:"+counter);
					if (logger.isDebugEnabled()) {
						e.printStackTrace();
					}
					throw e;
				}
			}
			//Start increment
			cal = (GregorianCalendar) BaseCalendar.addDays(cal, 1);
			++counter;
			//End increment
		}
	}
	
}
